package gold.contest;

import gold.utils.InputUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC6164 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int maximumSum(int[] nums) {
            Map<Integer, PriorityQueue<Integer>> cntMap = new HashMap<>();
            for (int num : nums) {
                final int bitSum = getBitSum(num);
                if (!cntMap.containsKey(bitSum)) cntMap.put(bitSum, new PriorityQueue<>(Comparator.reverseOrder()));
                cntMap.get(bitSum).add(num);
            }

            int maxVal = Integer.MIN_VALUE;
            for (Integer bitSum : cntMap.keySet()) {
                if (cntMap.get(bitSum).size() < 2) continue;
                int first = cntMap.get(bitSum).poll(), second = cntMap.get(bitSum).poll();
                maxVal = Math.max(maxVal, first + second);
            }

            return maxVal == Integer.MIN_VALUE ? -1 : maxVal;
        }

        public int getBitSum(int num) {
            int bitSum = 0;
            while (num > 0) {
                bitSum += num % 10;
                num /= 10;
            }
            return bitSum;
        }
    }

    public void run() {
//        System.out.println(new Solution().getBitSum(115013));
        System.out.println(new Solution().maximumSum(InputUtil.toIntegerArray("[279,169,463,252,94,455,423,315,288,64,494,337,409,283,283,477,248,8,89,166,188,186,128]")));
        System.out.println(new Solution().maximumSum(InputUtil.toIntegerArray("[4,6,10,6]")));
        System.out.println(new Solution().maximumSum(InputUtil.toIntegerArray("[18,43,36,13,7]")));
        System.out.println(new Solution().maximumSum(InputUtil.toIntegerArray("[10,12,19,14]")));
    }

    public static void main(String[] args) throws Exception {
        LC6164 an = new LC6164();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
